<template>
  <div class="categories">
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>分类列表</span>
          <div>
            <el-button type="primary" @click="handleAdd">添加分类</el-button>
          </div>
        </div>
      </template>
      
      <el-table
        :data="categoryList"
        style="width: 100%"
        v-loading="loading"
        row-key="id"
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="分类名称" />
        <el-table-column prop="parentId" label="父级分类" width="120">
          <template #default="scope">
            <span>{{ getParentName(scope.row.parentId) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 添加/编辑分类对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" />
        </el-form-item>
        <el-form-item label="父级分类" prop="parentId">
          <el-select v-model="categoryForm.parentId" placeholder="请选择父级分类" clearable>
            <el-option
              v-for="category in parentCategories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="categoryForm.sort"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCategory">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'Categories',
  setup() {
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    const categoryFormRef = ref(null)
    
    // 分类表单
    const categoryForm = reactive({
      id: null,
      name: '',
      parentId: '',
      sort: 0
    })
    
    // 表单验证规则
    const categoryRules = {
      name: [
        { required: true, message: '请输入分类名称', trigger: 'blur' }
      ]
    }
    
    // 模拟分类数据
    const categoryList = ref([
      {
        id: 1,
        name: '技术',
        parentId: 0,
        sort: 1,
        createTime: '2023-05-01 10:00:00'
      },
      {
        id: 2,
        name: '文学',
        parentId: 0,
        sort: 2,
        createTime: '2023-05-01 10:00:00'
      },
      {
        id: 3,
        name: '历史',
        parentId: 0,
        sort: 3,
        createTime: '2023-05-01 10:00:00'
      },
      {
        id: 4,
        name: '编程',
        parentId: 1,
        sort: 1,
        createTime: '2023-05-02 10:00:00'
      },
      {
        id: 5,
        name: '前端',
        parentId: 4,
        sort: 1,
        createTime: '2023-05-03 10:00:00'
      }
    ])
    
    // 获取父级分类选项（排除自己和子分类）
    const parentCategories = ref([])
    
    const getParentName = (parentId) => {
      if (!parentId || parentId === 0) return '无'
      const parent = categoryList.value.find(item => item.id === parentId)
      return parent ? parent.name : '未知'
    }
    
    const updateParentCategories = () => {
      parentCategories.value = categoryList.value.filter(item => 
        item.id !== categoryForm.id && 
        !isChildCategory(item.id, categoryForm.id)
      )
    }
    
    // 检查是否为子分类
    const isChildCategory = (childId, parentId) => {
      if (!parentId) return false
      if (childId === parentId) return true
      
      const child = categoryList.value.find(item => item.id === childId)
      if (!child || !child.parentId) return false
      
      if (child.parentId === parentId) return true
      
      return isChildCategory(child.parentId, parentId)
    }
    
    const handleAdd = () => {
      dialogTitle.value = '添加分类'
      // 重置表单
      Object.keys(categoryForm).forEach(key => {
        categoryForm[key] = key === 'sort' ? 0 : ''
      })
      updateParentCategories()
      dialogVisible.value = true
    }
    
    const handleEdit = (row) => {
      dialogTitle.value = '编辑分类'
      // 填充表单数据
      Object.keys(categoryForm).forEach(key => {
        categoryForm[key] = row[key]
      })
      updateParentCategories()
      dialogVisible.value = true
    }
    
    const handleDelete = (row) => {
      // 检查是否有子分类
      const hasChildren = categoryList.value.some(item => item.parentId === row.id)
      if (hasChildren) {
        ElMessage.error('该分类下有子分类，不能删除')
        return
      }
      
      ElMessageBox.confirm(
        `确定要删除分类《${row.name}》吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 模拟删除操作
        const index = categoryList.value.findIndex(item => item.id === row.id)
        if (index !== -1) {
          categoryList.value.splice(index, 1)
          ElMessage.success('删除成功')
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    }
    
    const confirmCategory = () => {
      categoryFormRef.value.validate((valid) => {
        if (valid) {
          if (categoryForm.id) {
            // 编辑操作
            const index = categoryList.value.findIndex(item => item.id === categoryForm.id)
            if (index !== -1) {
              // 更新数据
              Object.keys(categoryForm).forEach(key => {
                categoryList.value[index][key] = categoryForm[key]
              })
              ElMessage.success('编辑成功')
            }
          } else {
            // 添加操作
            const newCategory = {
              id: Math.max(...categoryList.value.map(item => item.id)) + 1,
              ...categoryForm,
              createTime: new Date().toLocaleString()
            }
            
            categoryList.value.push(newCategory)
            ElMessage.success('添加成功')
          }
          
          dialogVisible.value = false
        } else {
          ElMessage.error('请填写正确的信息')
        }
      })
    }
    
    return {
      loading,
      dialogVisible,
      dialogTitle,
      categoryFormRef,
      categoryForm,
      categoryRules,
      categoryList,
      parentCategories,
      getParentName,
      handleAdd,
      handleEdit,
      handleDelete,
      confirmCategory
    }
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>